<template>
	<scroll-view scroll-y class="favorites-page">
		<view v-if="favorites.length === 0" class="empty-message">
			您还没有收藏任何商品。
		</view>
		<view class="details" v-for="(item, index) in favorites" :key="item.id">
			<view class="pic">
				<image :src="item.img" mode="aspectFit" class="content-image"></image>
			</view>
			<view class="text">
				<view class="title">{{ item.name }}</view>
				<!-- 其他商品信息 -->
				<view class="fav" style="margin: 5px; display: flex; justify-content: end;">
					<uni-fav :checked="item.isFav" @click="favObj(item)"></uni-fav>
				</view>
			</view>
		</view>
	</scroll-view>
</template>
<script setup>
	import {
		ref,
		onShow
	} from 'vue';
	import {
		CONFIG
	} from '../../utils/config';
	import {
		userStore
	} from '../../store/userStore';

	const store = userStore();
	const favorites = ref([]);

	onShow(async () => {
		if (store.isLogin) {
			try {
				const response = await uni.request({
					url: `${CONFIG.leandcloud_url}/1.1/classes/star`,
					method: 'GET',
					data: {
						where: {
							username: store.userInfo.username
						}
					}
				});
				if (response.statusCode === 200) {
					favorites.value = response.data.results;
				}
			} catch (error) {
				console.error('Failed to fetch favorites:', error);
			}
		} else {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}
	});

	function favObj(item) {
		item.isFav = !item.isFav;
		// 这里添加发送到服务器的逻辑，更新收藏状态
		console.log(`Item ${item.name} is now ${item.isFav ? 'favorited' : 'unfavorited'}`);
	}
</script>

<style scoped>
	body{
		background: url('/static/images/1.png');
	}
	.favorites-page {
		padding: 20px;
	}

	.empty-message {
		color: #888;
		text-align: center;
		margin-top: 100px;
	}

	.details {
		margin-bottom: 20px;
	}

	.pic {
		width: 100%;
		height: 200px;
		margin-bottom: 10px;
	}

	.content-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.title {
		font-size: 20px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.fav {
		margin-top: 10px;
	}
</style>